package com.example.camera1;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private static int REQ_1 = 1;
    private static int REQ_2 = 2;
    private ImageView imageView;
    private String mFilePath;//路径
    private Uri imageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.imageView);
    }

    public void startCamera(View v) {
        //使用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, REQ_1);
    }

    public void startCamera2(View v) {
        //通过文件路径来获得原图，提高画质
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
/**这里是不安全的访问方式（启动intent时会直接闪退）安卓7.0以上使用共享文件形式
 * //        Uri photoUri=Uri.fromFile(new File(mFilePath));    //从文件中读取
 * //        intent.putExtra(MediaStore.EXTRA_OUTPUT,photoUri);//将output路径指向photoUri
 * //        //因为要访问sd卡读取文件
 * //        //所以要在manifest中添加对应权限
 * //        startActivityForResult(intent, REQ_2);
 */
//解决方案
        imageUri = getImageUri();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, REQ_2);
    }

    public Uri getImageUri() {
        File file = new File(Environment.getExternalStorageDirectory(),
                "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
//            boolean mkdirs() 创建此抽象路径名指定的目录，包括所有必需但不存在的父目录。
        }
        String path = file.getPath();//文件路径
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            //低于7.0
            imageUri = Uri.fromFile(file);
        } else {
            //兼容安卓7.0 使用共享文件形式
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, path);
            imageUri = this.getApplication().getContentResolver().
                    insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);

        }
        return imageUri;
    }

    public static String getFilePathFromUri(Context context, Uri uri) {  //从uri中得到path
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns
                    .DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //这个方法得到的图片画质很低，因为data的数据存储有限，系统会自动缩略data
        if (resultCode == RESULT_OK) {
            if (requestCode == REQ_1) {
                if (data != null) {
                    Bundle bundle = data.getExtras();//得到数据
                    Bitmap bitmap = (Bitmap) bundle.get("data");
                    imageView.setImageBitmap(bitmap);
                } else {
                    Toast.makeText(getApplicationContext(), "data为空!", Toast.LENGTH_SHORT).show();
                }

            } else if (requestCode == REQ_2) {
                FileInputStream fis = null;
                try {//将文件转为bitmap
                    mFilePath=getFilePathFromUri(MainActivity.this,imageUri);
                    fis = new FileInputStream(mFilePath);//之前忘记设置mFilePath
                    Bitmap bitmap = BitmapFactory.decodeStream(fis);
                    imageView.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}